package simple.utils.concurrent;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created with IntelliJ IDEA.
 * User: rehak
 * Date: 12/13/13
 * Time: 10:18 AM
 * To change this template use File | Settings | File Templates.
 */
public class MultiCounter {

    private final ConcurrentHashMap<String, AtomicLong> cnts = new ConcurrentHashMap<>();

    public MultiCounter() {

    }

    public long incrementAndGet(String cntName) {
        AtomicLong al = cnts.get(cntName);
        if (al == null) {
            al = new AtomicLong(0);
            AtomicLong old = cnts.putIfAbsent(cntName, al);
            if (old != null) {
                al = old;
            }
        }
        return al.incrementAndGet();
    }

    public long addAndGet(String cntName, long val) {
        AtomicLong al = cnts.get(cntName);
        if (al == null) {
            al = new AtomicLong(0);
            AtomicLong old = cnts.putIfAbsent(cntName, al);
            if (old != null) {
                al = old;
            }
        }
        return al.addAndGet(val);
    }

    public long get(String cntName) {
        AtomicLong c = cnts.get(cntName);
        if (c == null) {
            return 0;
        } else {
            return c.get();
        }
    }

}
